Vue.component('yl-goods', {
    template: `<el-dialog id="ylGoods" title="商品选择" :visible.sync="visibleDialog" width="80vw">
        <el-form :inline="true" :form="form">
            <el-form-item>
                <el-input v-model.trim="Article_Name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model.trim="selectbrand" collapse-tags multiple style="width: 100%;" clearable placeholder="请选择商品品牌">
                    <el-option v-for="item in brand" :key="item.Brand_SerialNumber" :label="item.Brand_Name" :value="item.Brand_SerialNumber"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-cascader v-model="selectclassify" filterable collapse-tags clearable placeholder="分类汇总"
                    :props="defaultProps" :options="classify" style="width: 300px"></el-cascader>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="onSerach">查询</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData.slice((form.page-1)*form.limit,form.page*form.limit)" :row-key="row=>row.Article_Specifications_SerialNumber"  stripe border height="55vh" style="width: 100%"  @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" width="50"></el-table-column>    
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Article_SerialNumber" show-overflow-tooltip label="商品内码"></el-table-column>
            <el-table-column align="center" prop="Article_Specifications_SerialNumber" show-overflow-tooltip label="规格内码"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Picture_URL" width="140" align="center" label="商品封面">
                <template v-slot="{row}">
                    <el-image fit="contain" :src="BASE_IMG + row.Picture_URL" style="width:100px;height: 100px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="Unit_Price1" show-overflow-tooltip label="吊牌价"></el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template v-slot="{row,$index}">
                    <el-button size="small" :disabled="loading" type="danger" @click="handleRemove($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="form.page" :page-sizes="[10, 30 , 60 ,100, 200, 300, 400]" :page-size="form.limit"
            layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" @click="submit()">确定</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'visible'],
    data() {
        return {
            visibleDialog: false,
            tableData: [],//详情
            form: {
                SQLSerialNumber: "A_business_article_info1",
                Condition: '',
                ExtensionCondition: '',
                page:1,
                limit:10,
            },
            total:0,
            activeName:"1",
            loading: false,
            brand:[],//全部品牌
            classify:[],//全部类别
            selectbrand:[],//已选品牌
            selectclassify:[],//已选分类
            Article_Name:'',//商品名称
            defaultProps:{
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_SerialNumber',
                multiple: true,
            },
            multipleSelection:[],
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
        },
    },
    methods: {
        onSerach(){
            let classify = []
            this.selectclassify.forEach(item => {
                classify = uniqueArr([...classify,...item]);
            })
            let sql = "and business_article_info.Article_Name LIKE '%"+this.Article_Name+"%'";
            //去重
            if(classify.length > 0){
                let str = "";
                classify.forEach((item,index)=>{
                    if (index==0) {
                        str =  "business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
                    }else {
                        str = str + " or business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
                    }
                })
                sql = sql + "and (" + str + ")\r\n"
            }
            if (this.selectbrand.length > 0) {
                let str = "";
                this.selectbrand.forEach((item,index)=>{
                    if (index==0) {
                        str =  "business_article_info.Brand_SerialNumber = '"+ item +"' \r\n"
                    }else {
                        str = str + " or business_article_info.Brand_SerialNumber = '"+ item +"' \r\n"
                    }
                })
                sql = sql + "and (" + str + ")\r\n"
            }
            this.form.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)))
            this.getList(this.form);
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        handleRemove(index){
            this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
        },  
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                console.log(json);
                //1.查询商品信息，并展示到页面上
                let str = "";//商品内码
                json.forEach(item=>{
                    if (item['商品编码']) {
                        if (str) {
                            str = str + " or business_article_info.Article_Code = '"+item['商品编码']+"'\r\n"
                        }else{
                            str = " business_article_info.Article_Code = '"+item['商品编码']+"'\r\n"
                        }
                    } else if (item['商品内码']) {
                        if (str) {
                            str = str+ " or business_article_info.Article_SerialNumber = '"+item['商品内码']+"'\r\n"
                        }else{
                            str = " business_article_info.Article_SerialNumber = '"+item['商品内码']+"'\r\n"
                        }
                    }
                })
                let sql = "and (" + str + ")";
                that.form.ExtensionCondition = base64.encode(unescape(encodeURIComponent(sql)));
                that.getList(that.form);
            }
        },
        getList(data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submit(){
            if (this.multipleSelection.length > 0) {
                this.$emit('success',this.multipleSelection);
                this.$emit('update:visible', false)
            }else{
                this.$message({
                    message: '请先选择商品',
                    type: 'warning'
                })
            }
        },
        download(){
            window.location.href = './download/导入商品编号查询商品.xlsx'
        },
        getData(){
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_brand',
                    Condition:"Row_Status='0'",
                },
                success: function (res) {
                    that.brand = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    },
    mounted(){
        this.getData();
    },
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Supplier_SerialNumber: '',
                Supplier_Name: '',//供应商名称
                Tax_Number: '',//所属地址
                Supplier_Address: '',
                Enterprise_Info_SerialNumber: '',
                address: '',
                Children: {
                    business_supplier_brand: [],
                    business_supplier_article: [],
                    business_supplier_bank_account: [{
                        Supplier_Bank_Account_SerialNumber: '',
                        Supplier_SerialNumber: '',
                        Bank_Name: '',
                        Account_Number: '',

                    }]
                }
            },
            page: {
                page: 1,
                limit: 10,
            },
            dialogVisible:false,
            selectBrand: [],
            selectArticle: [],
            business_supplier_article: [],
            value: [],
            address: '',
            rules: {
                Supplier_Name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
                address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
            },
            city: [],
            brand: [],
            article: [],
            loading: false,
            article_specifications: [],
        }
    },
    mounted() {
        const Supplier_SerialNumber = sessionStorage.getItem("Supplier_SerialNumber")
        this.getData(Supplier_SerialNumber);
    },
    methods: {
        getData(DocumentSerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: "business_brand",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.brand = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                url: absolutepath() + "utils/city.json",
                type: "GET",
                success: function (data) {
                    that.city = data
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalGetDataStructure`,
                type: 'POST',
                data: {
                    DocumentSerialNumber,
                    Data: JSON.stringify({ business_supplier_info: { business_supplier_brand: {}, business_supplier_bank_account: {}, business_supplier_article: {} } }),
                    Condition: ""
                },
                success: function (data) {
                    if (data.business_supplier_info.length > 0) {
                        that.form = data.business_supplier_info[0];
                        that.value = data.business_supplier_info[0].Supplier_Address.split('/').slice(0, 3)
                        that.address = data.business_supplier_info[0].Supplier_Address.split('/')[3];
                        let sql = "";
                        that.form.Children.business_supplier_article.filter(i=>i.Row_Status != '1').forEach(i=>{
                            if (sql) {
                                sql = sql + " or business_article_specifications.Article_Specifications_SerialNumber = '" + i.Article_Specifications_SerialNumber +"'\r\n"
                            } else {
                                sql = sql + " business_article_specifications.Article_Specifications_SerialNumber = '" + i.Article_Specifications_SerialNumber +"'\r\n"
                            }
                        })
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                            type: 'POST',
                            data:{
                                SQLSerialNumber: "A_business_article_info1",
                                Condition: '',
                                ExtensionCondition: base64.encode(`and (${sql})`),
                            },
                            success: function (Result) {
                                Result.forEach(item=>{
                                    that.business_supplier_article.push({
                                        Article_SerialNumber: item.Article_SerialNumber,
                                        Article_Specifications_SerialNumber: item.Article_Specifications_SerialNumber,
                                        Article_Name:item.Article_Name,
                                        Specifications_Name:item.Specifications_Name,
                                        Picture_URL:item.Picture_URL,
                                    })
                                })
                            },
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        });
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getArticle(data){
            data.forEach(item=>{
                this.business_supplier_article.push({
                    Supplier_Article_SerialNumber: this.form.Supplier_SerialNumber + '-' + item.Article_Specifications_SerialNumber,
                    Supplier_SerialNumber: this.form.Supplier_SerialNumber,
                    Article_SerialNumber: item.Article_SerialNumber,
                    Article_Specifications_SerialNumber: item.Article_Specifications_SerialNumber,
                    Article_Name:item.Article_Name,
                    Specifications_Name:item.Specifications_Name,
                    Picture_URL:item.Picture_URL,
                })
            })
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true
                    that.form.Supplier_Address = `${this.value[0]}/${this.value[1]}/${this.value[2]}/${this.address}`
                    
                    //删除的
                    that.form.Children.business_supplier_brand.forEach(item => {
                        if (!that.business_supplier_article.some(i=>i.Brand_SerialNumber==item.Brand_SerialNumber)) {
                            item.Row_Status = '1'
                        }
                    })
                    
                    

                    that.business_supplier_article.forEach(item=>{
                        if (!that.form.Children.business_supplier_brand.some(i=>i.Brand_SerialNumber == item.Brand_SerialNumber)) {
                            that.form.Children.business_supplier_brand.push({
                                Supplier_Brand_SerialNumber: '',
                                Supplier_SerialNumber:that.form.Supplier_SerialNumber,
                                Brand_SerialNumber:item.Brand_SerialNumber,
                            })   
                        }
                    })
                    that.form.Children.business_supplier_article.forEach(item => {
                        //判断每个商品是否是原来就有的,是要带上原值
                        if (that.business_supplier_article.some(i => i.Article_Specifications_SerialNumber == item.Article_Specifications_SerialNumber)) {
                            let obj = deepClone(that.business_supplier_article.filter(i => i.Article_Specifications_SerialNumber == item.Article_Specifications_SerialNumber)[0]);
                            let Supplier_Article_SerialNumber = obj.Supplier_Article_SerialNumber;
                            let newObj = {...obj,...item};
                            for (let key in newObj) {
                                item[key] = newObj[key]
                            }
                            item.Supplier_Article_SerialNumber = Supplier_Article_SerialNumber;
                            item.Row_Status = '0'
                        }else{
                            item.Row_Status = '1';
                        }
                    })
                    that.business_supplier_article.forEach(item=>{
                        if (!that.form.Children.business_supplier_article.some(i=>i.Article_Specifications_SerialNumber== item.Article_Specifications_SerialNumber)) {
                            // item.Row_Status = '1';
                            that.form.Children.business_supplier_article.push(item);
                        }
                    })
                    const { add, modify } = that.deal()
                    let data = {}
                    if (add == null) {
                        data = { Data: JSON.stringify({ Modify: { business_supplier_info: [modify] },Add:{base_operation_log:[generateLog('修改供应商(供应商名称:'+that.form.Supplier_Name+")", '平台端操作', 'business_supplier_info', JSON.stringify({ Modify: { business_supplier_info: [modify] } }))]} }) }
                    } else {
                        data = {
                            Data: JSON.stringify({ Modify: { business_supplier_info: [modify] }, 
                                Add: { 
                                    business_supplier_info: [add] ,
                                    base_operation_log:[generateLog('修改供应商(供应商名称:'+that.form.Supplier_Name+")", '平台端操作', 'business_supplier_info', JSON.stringify({ Modify: { business_supplier_info: [modify] },Add:{ business_supplier_info: [add] } }))]
                                } 
                            }),
                        }
                    }
                    $.ajax({
                        headers:requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data,
                        success: function (res) {
                            if (res.Status == 'success') {
                                that.$message.success("提交成功");
                                window.history.go(-1);
                            } else {
                                that.$message.error("提交失败，请稍后再试");
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false;
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        deal() {
            const add = deepClone(this.form)
            const modify = deepClone(this.form)

            let add_business_supplier_brand = [], modify_business_supplier_brand = []
            let add_business_supplier_bank_account = [], modify_business_supplier_bank_account = []
            let add_business_supplier_article = [], modify_business_supplier_article = []

            for (const i in modify.Children.business_supplier_brand) {
                const obj = modify.Children.business_supplier_brand[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_supplier_brand.push(obj)
                } else {
                    modify_business_supplier_brand.push(obj)
                }
            }
            for (const i in modify.Children.business_supplier_bank_account) {
                const obj = modify.Children.business_supplier_bank_account[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_supplier_bank_account.push(obj)
                } else {
                    modify_business_supplier_bank_account.push(obj)
                }
            }
            for (const i in modify.Children.business_supplier_article) {
                const obj = modify.Children.business_supplier_article[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_supplier_article.push({...obj,Shelf_Date:getYMDHMSDate()})
                } else {
                    modify_business_supplier_article.push(obj)
                }
            }
            add.Children.business_supplier_brand = add_business_supplier_brand
            modify.Children.business_supplier_brand = modify_business_supplier_brand

            add.Children.business_supplier_bank_account = add_business_supplier_bank_account
            modify.Children.business_supplier_bank_account = modify_business_supplier_bank_account
            
            add.Children.business_supplier_article = add_business_supplier_article
            modify.Children.business_supplier_article = modify_business_supplier_article

            if (add_business_supplier_bank_account.length == 0 && add_business_supplier_brand.length == 0 && add_business_supplier_article.length == 0) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        add_supplier_bank_account() {//添加账户
            this.form.Children.business_supplier_bank_account.push({
                Supplier_Bank_Account_SerialNumber: '',
                Supplier_SerialNumber: this.form.Supplier_SerialNumber,
                Bank_Name: '',
                Account_Number: '',
            })
        },
        remove_supplier_bank_account() {//删除账户
            if (this.form.Children.business_supplier_bank_account.filter(item => item.Row_Status != '1').length > 1) {
                let i = this.form.Children.business_supplier_bank_account.filter(item => item.Row_Status != '1').length - 1
                let obj = this.form.Children.business_supplier_bank_account.filter(item => item.Row_Status != '1')[i]
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this.form.Children.business_supplier_bank_account.pop()
                } else {
                    this.form.Children.business_supplier_bank_account.filter(item => item.Row_Status != '1')[i].Row_Status = '1';
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        handleSizeChange(val) {
            this.page.page = 1;
            this.page.limit = val;
        },
        handleCurrentChange(val) {
            this.page.page = val;
        },
        handleRemove(row, index) {//移除当前行
            this.business_supplier_article =  this.business_supplier_article.filter((i, id) => id != (this.page.page - 1) * this.page.limit + index)
        },
    }
})